﻿using D.Wx.Dtos;
using D.Wx.Entities;
using FreeSql;
using Microsoft.IdentityModel.Tokens;

namespace D.Wx.IRepository
{
    public class SysAdminEntityRepository : ISysAdminEntityRepository
    {
        private readonly IUnitOfWork _uow;
        private readonly IFreeSql _freeSql;
        public SysAdminEntityRepository(IFreeSql freeSql, IUnitOfWork uow)
        {
            _freeSql = freeSql;
            _uow = uow;
        }

        /// <summary>
        /// 获取最后一个分配的人
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public async Task<SysAdminEntity> GetNextAdminId()
        {
            return await _freeSql.Select<SysAdminEntity>()
                              .Where(m => m.IsPush.Value && m.RoleId == "2" && m.Status.Value && !m.DeleteFlag)
                              .OrderBy(m => m.AssignTotalCount)
                              .FirstAsync();
        }

        public async Task<int> Add(SysAdminEntity model)
        {
            return await _freeSql.Insert<SysAdminEntity>(model).ExecuteAffrowsAsync();
        }

        public async Task<int> Delete(List<string> ids)
        {
            return await _freeSql.Delete<SysAdminEntity>().Where(m => ids.Contains(m.Id)).ExecuteAffrowsAsync();
        }
        public async Task<int> Update(SysAdminEntity model)
        {
            return await _freeSql.Update<SysAdminEntity>().SetSource(model).ExecuteAffrowsAsync();
        }

        public async Task<AdminEntityOutput> Get(string id)
        {
            return await _freeSql.Select<SysAdminEntity>().Where(m => m.Id == id).FirstAsync(m => new AdminEntityOutput
            {
                Id = m.Id,
                Account = m.Account,
                AssignTotalCount = m.AssignTotalCount,
                IsPush = m.IsPush,
                CreateTime = m.CreateTime,
                UpdateTime = m.UpdateTime,
                DeleteFlag = m.DeleteFlag,
                CreateUser = m.CreateUser,
                Descption = m.Descption,
                LastLoginIp = m.LastLoginIp,
                LastLoginTime = m.LastLoginTime,
                LoginTotalCount = m.LoginTotalCount,
                NickName = m.NickName,
                UserGroupId = m.UserGroupId,
                WeiXin = m.WeiXin,
                WeiXinOpenId = m.WeiXinOpenId,
                Status = m.Status,
                UpdateUser = m.UpdateUser,
                RoleId = m.RoleId,
                UUID = m.UUID,
            });
        }

        public async Task<PageModel<AdminEntityOutput>> QueryPage(SysAdminEntityPageQuery pageQuery)
        {
            var sqlQuery = _freeSql.Select<SysAdminEntity, SysUserGroupEntity>()
                               .LeftJoin((m, u) => m.UserGroupId == u.Id)
                              .Where((m, u) => !m.DeleteFlag)
                              .WhereIf(!string.IsNullOrEmpty(pageQuery.Name), (m, u) => m.NickName.Contains(pageQuery.Name) || m.UUID.Contains(pageQuery.Name))
                              .WhereIf(pageQuery.Status != null, (m, u) => m.Status == pageQuery.Status)
                              .OrderByDescending((m, u) => m.CreateTime);

            var totalCount = await sqlQuery.CountAsync();
            return new PageModel<AdminEntityOutput>()
            {
                PageNo = pageQuery.Current.Value,
                PageSize = pageQuery.PageSize.Value,
                TotalCount = totalCount,
                TotalPage = (totalCount + pageQuery.PageSize.Value - 1) / pageQuery.PageSize.Value,
                Data = await sqlQuery.Page(pageQuery.Current.Value, pageQuery.PageSize.Value).ToListAsync((m, u) => new AdminEntityOutput()
                {
                    Id = m.Id,
                    Account = m.Account,
                    AssignTotalCount = m.AssignTotalCount,
                    IsPush = m.IsPush,
                    UserGroupId = u.Name,
                    WeiXin = m.WeiXin,
                    WeiXinOpenId = m.WeiXinOpenId,
                    CreateTime = m.CreateTime,
                    UpdateTime = m.UpdateTime,
                    DeleteFlag = m.DeleteFlag,
                    CreateUser = m.CreateUser,
                    Descption = m.Descption,
                    LastLoginIp = m.LastLoginIp,
                    LastLoginTime = m.LastLoginTime,
                    LoginTotalCount = m.LoginTotalCount,
                    NickName = m.NickName,
                    Status = m.Status,
                    UpdateUser = m.UpdateUser,
                    RoleId = m.RoleId,
                    UUID = m.UUID,
                })
            };
        }

        public async Task<SysAdminEntity> Login(string account, string pwd)
        {
            return await _freeSql.Select<SysAdminEntity>().Where(m => m.Account == account && m.Pwd == pwd).FirstAsync();
        }
    }
}
